import fs from 'fs';
import path from 'path';
import os from 'os';
import crypto from 'crypto';
import chalk from 'chalk';
import { Logger } from '../utils/logger.js';

export class ConfigManager {
  constructor() {
    this.configDir = path.join(os.homedir(), '.sftp-cli');
    this.configFile = path.join(this.configDir, 'config.json');
    // 使用固定的加密密钥（基于用户主目录的哈希）
    this.encryptionKey = crypto.createHash('sha256')
      .update(os.homedir())
      .digest();
    this.ensureConfigDir();
  }

  // 加密数据
  encrypt(data) {
    const iv = crypto.randomBytes(16);
    const cipher = crypto.createCipheriv('aes-256-cbc', this.encryptionKey, iv);
    let encrypted = cipher.update(JSON.stringify(data), 'utf-8', 'hex');
    encrypted += cipher.final('hex');
    return iv.toString('hex') + ':' + encrypted;
  }

  // 解密数据
  decrypt(encryptedData) {
    try {
      const parts = encryptedData.split(':');
      const iv = Buffer.from(parts[0], 'hex');
      const encrypted = parts[1];
      const decipher = crypto.createDecipheriv('aes-256-cbc', this.encryptionKey, iv);
      let decrypted = decipher.update(encrypted, 'hex', 'utf-8');
      decrypted += decipher.final('utf-8');
      return JSON.parse(decrypted);
    } catch (error) {
      Logger.error(`解密失败: ${error.message}`);
      return null;
    }
  }

  ensureConfigDir() {
    if (!fs.existsSync(this.configDir)) {
      fs.mkdirSync(this.configDir, { recursive: true });
      Logger.success(`配置目录已创建: ${this.configDir}`);
    }
  }

  loadConfigs() {
    try {
      if (fs.existsSync(this.configFile)) {
        const data = fs.readFileSync(this.configFile, 'utf-8');
        // 尝试解密，如果失败则当作纯文本处理（用于向后兼容）
        if (data.includes(':') && !data.startsWith('{')) {
          const decrypted = this.decrypt(data);
          return decrypted || {};
        }
        return JSON.parse(data) || {};
      }
      return {};
    } catch (error) {
      Logger.warn(`读取配置文件失败: ${error.message}`);
      return {};
    }
  }

  saveConfigs(configs) {
    try {
      const encrypted = this.encrypt(configs);
      fs.writeFileSync(
        this.configFile,
        encrypted,
        'utf-8'
      );
      // 设置配置文件权限为 600（仅所有者可读写）
      fs.chmodSync(this.configFile, 0o600);
      Logger.success('配置已保存（已加密）');
    } catch (error) {
      Logger.error(`保存配置文件失败: ${error.message}`);
      throw error;
    }
  }

  getConfig(name) {
    const configs = this.loadConfigs();
    return configs[name];
  }

  saveConfig(name, config) {
    const configs = this.loadConfigs();
    configs[name] = {
      ...config,
      createdAt: config.createdAt || new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    this.saveConfigs(configs);
  }

  deleteConfig(name) {
    const configs = this.loadConfigs();
    delete configs[name];
    this.saveConfigs(configs);
  }

  listConfigs() {
    return this.loadConfigs();
  }

  validateConfig(config) {
    const errors = [];

    if (!config.host) errors.push('缺少必填项: host');
    if (!config.username) errors.push('缺少必填项: username');
    if (!config.port) errors.push('缺少必填项: port');
    if (!config.authType) errors.push('缺少必填项: authType');

    if (config.authType === 'password' && !config.password) {
      errors.push('密码认证需要提供密码');
    }

    if (config.authType === 'key' && !config.privateKeyPath) {
      errors.push('私钥认证需要提供私钥路径');
    }

    if (config.authType === 'key' && config.privateKeyPath) {
      if (!fs.existsSync(config.privateKeyPath)) {
        errors.push(`私钥文件不存在: ${config.privateKeyPath}`);
      }
    }

    return {
      valid: errors.length === 0,
      errors,
    };
  }
}
